import {colorList, configuration as config} from './graphConfig.js'

let configuration = config

let clusterMap = new Map();
let clusterId = 0;
let legendData = {
    nodes: [],
    edges: []
}

// 处理图谱数据
function handlerGraphData(params) {
    let {data, configuration: config} = params
    configuration = config
    // 处理节点数据
    data.nodes.forEach(function (node) {
        //设置节点属性
        node.attributes = {...node}
        if (!node.label && configuration.nodeLabel) node.label = node[configuration.nodeLabel]
        if (!node.id && configuration.nodeId) node.id = node[configuration.nodeId]
        //设置节点不同类型的颜色-------------------------
        if (node[configuration.nodeType] && clusterMap.get(node[configuration.nodeType]) === undefined) {
            clusterMap.set(node[configuration.nodeType], clusterId);
            clusterId++;
        }
        const cid = clusterMap.get(node[configuration.nodeType]);
        if (!node.style) node.style = {}
        node.style.fill = colorList[cid % colorList.length];
        node.style.stroke = colorList[cid % colorList.length];
        //获取节点类型数据--------------------------
        if (!legendData.nodes.find(v => v.id === node[configuration.nodeType])) {
            legendData.nodes.push({
                id: node[configuration.nodeType],
                label: node[configuration.nodeType]
            })
        }
    });
    // 处理边数据
    data.edges.forEach(edge => {
        //设置边的属性
        edge.attributes = {...edge}
        if (!edge.id && configuration.edgeId) edge.id = edge[configuration.edgeId]
        if (!edge.label && configuration.edgeLabel) edge.label = edge[configuration.edgeLabel]
        if (!edge.source && configuration.source) edge.source = edge[configuration.source]
        if (!edge.target && configuration.target) edge.target = edge[configuration.target]
        // 设置边不同类型的颜色-----------------------------------------
        const currentNode = data.nodes.find(v => v.id === edge.source)
        let cid = clusterMap.get(currentNode[configuration.nodeType])
        edge.style = {
            stroke: colorList[cid % colorList.length]
        }
        // 设置边类型数据
        //...
    })
    return data
}

// 处理节点和边类型数据
function handlerLegendData() {
    let legendFilterCondition = {}
    legendData.nodes.forEach(legendNode => {
        const cid = clusterMap.get(legendNode.id);
        // 设置legend节点颜色
        legendNode.style = {
            fill: colorList[cid % colorList.length]
        };
        // 设置legend节点筛选条件
        legendFilterCondition[legendNode.id] = (d) => {
            return d[configuration.nodeType] === legendNode.id;
        }
    })
    return {legendType: legendData, legendFilterCondition}
}

// 深拷贝
function deepCopyData(params) {
    if (window.structuredClone) {
        return structuredClone(params)
    } else {
        return JSON.parse(JSON.stringify(params));
    }
}

export {handlerLegendData, handlerGraphData, deepCopyData}
